from datetime import datetime

from rest_framework.views import APIView
from rest_framework.response import Response
from django.db import connection
from dvadmin.system.core.wos import DownloadTaskManager, Agent

manager = DownloadTaskManager()
agents = {}


def start_agent(agent_id):
    # for id in agent_id:
    #     if id not in agents:
    #         agents[id] = Agent(id)
    cursor = connection.cursor()
    print(datetime.now())
    cursor.execute(f"UPDATE agent SET status=1 WHERE id IN ({', '.join(map(str, agent_id))})")
    print(datetime.now())
    cursor.close()
    return True


def close_agent(agent_id):
    for id in agent_id:
        if id in agents:
            del agents[id]
    cursor = connection.cursor()
    print(datetime.now())
    cursor.execute(f"UPDATE agent SET status=0 WHERE id IN ({', '.join(map(str, agent_id))})")
    print(datetime.now())
    cursor.close()
    return True


# 部署爬取任务
class DownloadTaskView(APIView):
    """
    爬取指定期刊及年份的文献数据
    """

    def post(self, request):
        # 获取请求负载中的数据
        data = request.data
        agent_id = data.get('id')
        years = data.get('years')
        # 分配爬取下载器
        if agent_id not in agents:
            agents[agent_id] = Agent(agent_id)
        if agents[agent_id].add_tasks(manager, years):
            return Response(data={"code": 2000, "msg": "爬取任务已部署"}, status=200)
        return Response(data={"code": 400, "msg": "部分爬取任务部署失败"}, status=200)


class AgentControlView(APIView):
    cases = {
        'start': lambda agent_id: start_agent(agent_id),
        'close': lambda agent_id: close_agent(agent_id),
    }
    """
    控制智能体状态(如开始或关闭)
    本方法采用的是将数据库持久化；也可以及进行更改，使用缓存持久化(例：Redis)
    """
    def get(self, request):
        print(f"1:{datetime.now()}")
        params = request.query_params
        agent_id = int(params.get('id'))
        action = params.get('action')
        end_agent_id = int(params.get('end_id') or agent_id)
        if end_agent_id<agent_id: return Response(data={"code": 400, "msg": "操作失败"}, status=200)
        agent_id_range = range(agent_id, end_agent_id + 1)
        print(f"2:{datetime.now()}")

        if self.cases[action](agent_id_range):
            return Response(data={"code": 2000, "msg": "操作成功"}, status=200)
        return Response(data={"code": 400, "msg": "操作失败"}, status=200)


# 上传期刊信息
class AgentUploadView(APIView):
    """
    上传期刊信息---插入新的agent
    """

    def post(self, request):
        # 获取请求负载中的列表数据
        data = request.data
        names = data.get('names')
        print(names)
        cursor = connection.cursor()
        for name in names:
            cursor.execute(f"INSERT INTO agent VALUE (DEFAULT,'{name}')")
        connection.commit()
        cursor.close()
        return Response(data={"code": 2000, "msg": "上传成功"}, status=200)
